﻿using DataCollection.Infrastructure;
using DataCollection.WinForm.ViewModel;

namespace DataCollection.WinForm.Forms
{
    public partial class AddDeviceForm : DCBaseForm
    {
        #region 属性

        private DeviceViewModel viewModel = null!;

        /// <summary>
        /// 需要绑定的控件
        /// </summary>
        private Dictionary<string, Control> ControlDict = new Dictionary<string, Control>();

        #endregion

        #region 自定义方法


        #endregion

        #region 系统事件
        public AddDeviceForm()
        {
            InitializeComponent();
            Header.Text = "添加设备";
            foreach (string name in Singleton.Instance.SerialPortList)
            {
                PortAddressSelect.Items.Add(name);
            }

            ControlDict.Add("number", DeviceNumberInput);
            ControlDict.Add("portAddress", PortAddressSelect);
            ControlDict.Add("baudrate", BaudrateSelect);
            ControlDict.Add("name", DeviceNameInput);
            ControlDict.Add("slaveAddress", SlaveAddressInput);
            ControlDict.Add("enable", DeviceStateSelect);
            ControlDict.Add("holdingRegisterCount", HRCountInput);
            ControlDict.Add("inputRegisterCount", IRCountInput);
            ControlDict.Add("coilStatusCount", DOCountInput);
            ControlDict.Add("inputStatusCount", DICountInput);
        }

        private void AddDeviceForm_Load(object sender, EventArgs e)
        {
            viewModel = new DeviceViewModel(DateTimeOffset.Now.ToUnixTimeSeconds());
            foreach (var item in ControlDict)
            {
                Bindings(item.Value, "Text", item.Key, viewModel);
            }
        }

        private void ConfirmButton_Click(object sender, EventArgs e)
        {
            viewModel.Apply();
            Response response = viewModel.Add();
            if (response.Code == Response.SuccessCode)
            {
                if (this.Owner != null)
                {
                    ManageDeviceForm frm = (ManageDeviceForm)this.Owner;
                    frm.LoadDeviceList();
                    frm.Success(response.Msg);
                }
                this.Close();
            }
            else
            {
                Error(response.Msg);
            }
        }

        private void Input_Click(object sender, EventArgs e)
        {
            AntdUI.Input input = (AntdUI.Input)sender;
            KeyBoardForm.input = input;
            KeyBoardForm frm = new KeyBoardForm();
            frm.ShowDialog(this);
        }
        #endregion


    }
}
